package it.polimi.reTravelDream.beans;

import it.polimi.reTravelDream.dto.CityDTO;
import it.polimi.reTravelDream.eao.CityEAOLocal;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.PostConstruct;
import javax.ejb.EJB;
import javax.enterprise.context.RequestScoped;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;

import org.primefaces.expression.impl.ThisExpressionResolver;



@ManagedBean(name="cityBean")
@SessionScoped
public class CityBean {

	@EJB
	private CityEAOLocal cityEAOLocal;
	
	private CityDTO cityDTO;
	private List<CityDTO> allCityList;
	
	private String errorName="";
	
	public CityBean(){
		this.cityDTO=new CityDTO();
		this.allCityList=new ArrayList<CityDTO>();
	}
	
	@PostConstruct
	public void getCities(){
		this.allCityList=cityEAOLocal.getAllCity();
	}
	
	public void add(){
		if (!this.checkName()) {
			return;
		}
		cityEAOLocal.addCity(this.cityDTO);
		this.allCityList=cityEAOLocal.getAllCity();
		this.cityDTO=new CityDTO();
	}
	
	private boolean checkName(){
		boolean value=true;
		List<CityDTO> cityDTOs=cityEAOLocal.getAllCity();
		for (CityDTO cDto: cityDTOs){
			if (cDto.getCity().equals(this.cityDTO.getCity())) {
				value=false;
				this.errorName="this city is already present";
			}else {
				this.errorName="";
			}
		}
		return value;
	}
	
	public void removeCity(CityDTO cityToRemove){
		this.cityEAOLocal.removeCity(cityToRemove);
		this.allCityList=cityEAOLocal.getAllCity();
	}
	
	public void editCity(CityDTO cityToEdit){
		
	}
	 


	
	
	/** getter and setter	 */
	public CityDTO getCityDTO() {
		return cityDTO;
	}

	public void setCityDTO(CityDTO cityDTO) {
		this.cityDTO = cityDTO;
	}

	public List<CityDTO> getAllCityList() {
		return allCityList;
	}

	public void setAllCityList(List<CityDTO> allCityList) {
		this.allCityList = allCityList;
	}

	public String getErrorName() {
		return errorName;
	}

	public void setErrorName(String errorName) {
		this.errorName = errorName;
	}
}